<template>
  <div class="vk-collapse">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineOptions, ref, provide, watch } from "vue";
import type { NameType } from "./types";
import { CollapseContextKey, CollapseProps, CollapseEmits } from "./types";

defineOptions({
  name: "VkCollapse",
});

const props = defineProps<CollapseProps>();
const emits = defineEmits<CollapseEmits>();
const activeNames = ref<NameType[]>(props.modelValue);
// 监听 props.modelValue 的变化
watch(
  () => props.modelValue,
  () => {
    activeNames.value = props.modelValue;
  }
);

// 判断点击的这个item的name是否存在于 activeNames 数组中
const handleItemClick = (item: NameType) => {
  // 开启手风琴模式
  if (props.accordion) {
    //  若点击的是自己就清空，否则，添加一个
    activeNames.value = [activeNames.value[0] === item ? "" : item];
  } else {
    const index = activeNames.value.indexOf(item);
    if (index > -1) {
      // 如果存在，删除数组中对应的这一项
      activeNames.value.splice(index, 1);
    } else {
      // 如果不存在，在数组中添加对应的这一项
      activeNames.value.push(item);
    }
  }

  emits("update:modelValue", activeNames.value);
  emits("change", activeNames.value);
};

provide(CollapseContextKey, {
  activeNames,
  handleItemClick,
});
</script>

<style scoped></style>
